package com.springboot.frame.oauth.server.security.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springboot.frame.oauth.server.mapper.SysResourcesMapper;
import com.springboot.frame.oauth.server.mapper.SysRoleMapper;
import com.springboot.frame.oauth.server.mapper.SysUserMapper;
import com.springboot.frame.oauth.server.model.SysResources;
import com.springboot.frame.oauth.server.model.SysRole;
import com.springboot.frame.oauth.server.model.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class SecurityUserService implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysResourcesMapper sysResourcesMapper;

    @Override
    public SysUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getAccount, username).last(" LIMIT 1"));
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        SysUserDetails vo = new SysUserDetails();
        BeanUtils.copyProperties(user, vo);
        if (user.getId().equals(1)) {
            getAdminPermission(vo);
        } else {
            List<SysRole> roles = sysRoleMapper.selectSysRolesByUid(user.getId());
            List<Integer> roleIds = roles.stream().map(SysRole::getId).collect(Collectors.toList());
            List<SysResources> resources = sysResourcesMapper.selectResourceByRoles(roleIds);
            vo.setRoles(roles);
            vo.setResources(resources);
        }
        return vo;
    }


    /**
     * 为管理员赋所有权限
     *
     * @param
     * @return
     */
    private SysUserDetails getAdminPermission(SysUserDetails details) {
        List<SysRole> roles = sysRoleMapper.selectList(new LambdaQueryWrapper<>());
        List<SysResources> resources = sysResourcesMapper.selectList(new LambdaQueryWrapper<>());
        details.setRoles(roles);
        details.setResources(resources);
        return details;
    }

}
